#include "StringUtil.h"
#include <algorithm>
#include <chrono>
#include <ctime>

#if defined(_WIN32)
#include <objbase.h>
#elif defined(__linux__)
// sudo apt-get install uuid-dev // ubuntu
#include <uuid/uuid.h>
#else
#error "uuid unsupport platform"
#endif

#define GUID_LEN 64

AMCAX_EXCHANGE_NAMESPACE_BEGIN 
namespace StringUtil
{

    std::string GenerateUUID()
    {

    #ifdef _WIN32
        char buf[GUID_LEN] = { 0 };
        GUID guid;

        if (CoCreateGuid(&guid))
        {
            return std::move(std::string(""));
        }
        sprintf(buf,
            "%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X",
            guid.Data1, guid.Data2, guid.Data3,
            guid.Data4[0], guid.Data4[1], guid.Data4[2],
            guid.Data4[3], guid.Data4[4], guid.Data4[5],
            guid.Data4[6], guid.Data4[7]);

        return std::move(std::string(buf));
    #elif __linux__
        char buf[GUID_LEN] = { 0 };

        uuid_t uu;
        // uuid_generate(uu);

        int32_t index = 0;
        for (int32_t i = 0; i < 16; i++)
        {
            int32_t len = i < 15 ?
                sprintf(buf + index, "%02X-", uu[i]) :
                sprintf(buf + index, "%02X", uu[i]);
            if (len < 0)
                return std::move(std::string(""));
            index += len;
        }

        return std::move(std::string(buf));
    #endif // WIN32

    }


    bool IsLastChar(const std::string s, const char ch)
    {
        if (s.empty())
            return false;
        return s.back() == ch;
    }

    std::string ToLowerCase(const std::string s)
    {
        std::string lower_str = s;
        std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);
        return lower_str;
    }

    std::string GetCurrentTime()
    {
        auto tp = std::chrono::system_clock::now();
        std::time_t t = std::chrono::system_clock::to_time_t(tp);
        std::tm* tm = std::localtime(&t);
        char buffer[80];
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm);
        return buffer ;//        return std::to_string(t);
    }

    
}

AMCAX_EXCHANGE_NAMESPACE_END